<?php
session_start();
require('functions.php');
require('mysqli_connect.php');
//User Validation...
if(isset($_COOKIE['ID']) && isset($_SESSION['ID']) && isset($_COOKIE['USER'])) { //it's mandatory to have all this variables set to validate, and continue with the page, Login set all this vars
	$user = validation1($_COOKIE['USER'], $_COOKIE['ID'], $_SESSION['ID'], $dbc);
	if(is_array($user)) { //validation done (correct)
		$webpage = '/timetables/files/timetables.php';
		$sections = array();
		$sections[] = 'share';
		$H = mysqli_real_escape_string($dbc, $_POST['H']);
		$D = mysqli_real_escape_string($dbc, $_POST['D']);
		//$user = mysqli_real_escape_string($dbc, $_POST['user']);
		$q = "select * from events where (hour='".$H.":00:00' and day='".$D."')";
		$r = @mysqli_query ($dbc, $q);
		$select = select($r);
			foreach($select as $event) {
				$q = "select * from share where (owner=".$user['iduser']." and idevent=".$event['idevent'].")";
				$r = @mysqli_query ($dbc, $q);
				$userown = mysqli_fetch_array($r, MYSQLI_ASSOC);
			if($userown) {
				echo "This task already exists";
				exit();
			}
		}
		
		$task = addslashes( trim ( strip_tags ($_POST['task'])));
		$descrip = addslashes( trim ( strip_tags ($_POST['descrip'])));			
		if(is_numeric($H) && sizeof($task) && sizeof($descrip))  {
		
			$q = "insert into events(hour, day, task, descrip) values ('".$H.":00:00', '".$D."', '".$task."', '".$descrip."')";
			$r = @mysqli_query ($dbc, $q);
			$event['idevent'] =  mysqli_insert_id($dbc);
			
			$q = "insert into share values (".$event['idevent'].", ".$user['iduser'].", ".$user['iduser'].")";
			$r = @mysqli_query ($dbc, $q);
			
			header('Location: ' .$webpage. '?curr='.$sections[0].'&ev='.$event['idevent']);
		}
		else {
		echo "incorrect data sended";
		//echo $task .' '. $descrip.' '.sizeof($_POST['D']);
		}
	}
 }

	
?>